package com.find.answer.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.find.answer.domain.dto.PageDto;
import com.find.answer.domain.http.Result;
import com.find.answer.domain.po.Category;
import com.find.answer.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Seon
 * @date 2022/10/19 11:03
 */
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/page")
    public Result<Page<Category>> getCategoryPage(PageDto pageDto) {
        Page<Category> page = new Page<>();
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("sort");
        page.setSize(pageDto.getPageSize());
        page.setCurrent(pageDto.getPage());
        Page<Category> queryResult = categoryService.page(page, wrapper);
        return Result.success(queryResult);
    }


    @PutMapping("")
    public Result<?> updateCategory(@RequestBody Category category) {
        try {
            categoryService.updateById(category);
            return Result.success("修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("修改失败");
        }
    }

    @PostMapping("")
    public Result<?> addCategory(@RequestBody Category category) {
        categoryService.save(category);
        return Result.success("添加成功");
    }

    @DeleteMapping("")
    public Result<?> deleteCategory(@RequestParam("ids") Long ids) {
        try {
            categoryService.remove(ids);
            return Result.success("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除失败，该分类还存在其他依赖");
        }
    }

    @GetMapping("/list")
    public Result<?> getListByType(@RequestParam(value = "type", required = false) Integer type) {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(type != null, Category::getType, type);
        wrapper.orderByAsc(Category::getType)
                .orderByAsc(Category::getSort)
                .orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(wrapper);
        return Result.success(list);
    }

}
